package com.wunu.smartlock1.service;

import com.wunu.smartlock1.net.NetComponent;
import com.wunu.smartlock1.net.api.AccountApi;
import com.wunu.smartlock1.net.param.LoginParam;
import com.wunu.smartlock1.net.response.ApiLoginResponse;
import com.wunu.smartlock1.net.response.LoginResult;

import java.io.IOException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AccountService {

    public LoginResult login(String phone, String password) throws IOException {
        AccountApi service = NetComponent.getRetrofit().create(AccountApi.class);
        LoginParam param = new LoginParam.Builder().countryCode("cc").phone(phone).password(password).build();
        ApiLoginResponse resp = null;
        try {
            final Call<ApiLoginResponse> call = service.login(param);
            resp = call.execute().body();
        }catch (Exception e){
            System.out.println("response exception "+e.getMessage());
            return null;
        }


        System.out.println("1登录返回结果:"+resp);
        System.out.println("登录返回结果:"+resp.getCode());
        //每个请求都带上token
        if (resp.ok()) {
            LoginResult loginResult = resp.getData();
            System.out.println("token: "+loginResult.getData().getToken());
            NetComponent.addTokenInterceptor(loginResult);
            return loginResult;
        }
        return null;
    }

    public Call<ApiLoginResponse> asyncLogin(String phone, String password) throws IOException {
        AccountApi service = NetComponent.getRetrofit().create(AccountApi.class);
        LoginParam param = new LoginParam.Builder().countryCode("cc").phone(phone).password(password).build();
        final Call<ApiLoginResponse> call = service.login(param);
        return call;
    }


//    public void asyncLogin(String phone, String password) throws IOException {
//        AccountApi service = NetComponent.getRetrofit().create(AccountApi.class);
//        LoginParam param = new LoginParam.Builder().countryCode("cc").phone(phone).password(password).build();
//        final Call<ApiLoginResponse> call = service.login(param);
//        call.enqueue(new Callback<ApiLoginResponse>() {
//
//            @Override
//            public void onResponse(Call<ApiLoginResponse> call, Response<ApiLoginResponse> response) {
//                ApiLoginResponse apiLoginResponse = response.body();
//                //每个请求都带上token
//                if (response.body().ok()) {
//                    LoginResult loginResult = apiLoginResponse.getData();
//                    System.out.println(loginResult.getToken());
//                    NetComponent.addTokenInterceptor(loginResult);
//                }
//            }
//
//            @Override
//            public void onFailure(Call<ApiLoginResponse> call, Throwable t) {
//                System.out.println(t.getMessage());
//            }
//        });
//    }
}
